package com.nf1000.balancelibrary.newbalance;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;

@SuppressLint("NewApi")
@SuppressWarnings("unused")
public class BlueSingleton{
	private static BlueSingleton uniqueInstance = null;  
	private static Handler mHandler;
	private boolean mConnected = false;
	private boolean mScanning = false;
	private boolean oncelinked = false;
	private BluetoothAdapter mBluetoothAdapter;

	private ServiceConnection mServiceConnection;
	static boolean isdoings = false;
	private Context scanActivity;
	
    private BlueSingleton() {

    }  
   
    public static BlueSingleton getInstance(Handler handler) {
       if (uniqueInstance == null) {  
           uniqueInstance = new BlueSingleton();  
       }  
       mHandler = handler;
       return uniqueInstance;  
    } 
    
    public void scanLeDevice(final boolean enable, Context context, ServiceConnection mServiceConnection) {
    	this.scanActivity = context;
    	this.mServiceConnection = mServiceConnection;
    	final BluetoothManager bluetoothManager = (BluetoothManager) scanActivity.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        if (enable) {
        	oncelinked = false;
            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    /**扫描回调*/
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
        	Message msg = mHandler.obtainMessage();
			msg.what = ActionConstant.ACTION_ON_LE_SCAN;
			Bundle b = new Bundle();
			b.putParcelable("device", (Parcelable) device);
			msg.setData(b); 
			mHandler.sendMessage(msg);
        }
    };

    public void linkout() {
    	if(mScanning && !mConnected) {
    		scanLeDevice(false, scanActivity, mServiceConnection);
    	}
    }
    public boolean getmScanning() {
    	return mScanning;
    }
    public void setmScanning(boolean b) {
    	mScanning = b;
    }
    public boolean getmConnected() {
    	return mConnected;
    }
    public void setmConnected(boolean b) {
    	if(b){
    		oncelinked = true;
    	}
    	mConnected = b;
    }
    public void setmServiceConnection(ServiceConnection mServiceConnection) {
    	this.mServiceConnection = mServiceConnection;
    }
    
    public static synchronized boolean isIsdoing() {
		return isdoings;
	}

	public static synchronized void setIsdoing(boolean isdoing) {
		isdoings = isdoing;
	}
}
